package org.example.mock;

import lombok.extern.slf4j.Slf4j;
import org.example.bean.Country;

import java.sql.*;
import java.util.*;

/**
 * 国家数据生成器，生成唯一国家名称数据并插入数据库
 */
@Slf4j
public class CountryGenerator {
    private static final String DB_URL = "jdbc:mysql://192.168.10.102/changchengfilm?requireSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "000000";
    private static final int BATCH_SIZE = 50;
    private static final int TOTAL_RECORDS = 50;

    private static final Random RANDOM = new Random();

    private static final List<String> COUNTRY_NAMES = List.of(
            "中国", "美国", "日本", "英国", "法国", "德国", "俄罗斯", "加拿大", "澳大利亚", "韩国",
            "意大利", "西班牙", "印度", "巴西", "墨西哥", "荷兰", "瑞士", "瑞典", "挪威", "丹麦",
            "芬兰", "比利时", "奥地利", "波兰", "土耳其", "沙特阿拉伯", "伊朗", "以色列", "阿联酋", "南非",
            "阿根廷", "智利", "哥伦比亚", "泰国", "马来西亚", "新加坡", "印度尼西亚", "菲律宾", "越南", "新西兰",
            "埃及", "尼日利亚", "肯尼亚", "加纳", "摩洛哥", "阿尔及利亚", "葡萄牙", "希腊", "乌克兰", "白俄罗斯"
    );

    public static void main(String[] args) {
        log.info("开始生成{}条唯一国家模拟数据并插入数据库", TOTAL_RECORDS);

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            // 清空现有数据
            clearExistingData(conn);

            List<Country> countryList = generateUniqueCountryData();
            insertToDatabase(countryList);
            log.info("数据插入完成");
        } catch (SQLException e) {
            log.error("数据库操作失败", e);
        }
    }

    /**
     * 清空countries表中的现有数据
     */
    private static void clearExistingData(Connection conn) throws SQLException {
        log.info("清空countries表中的现有数据");
        try (Statement stmt = conn.createStatement()) {
            stmt.executeUpdate("DELETE FROM countries");
            // 如果需要重置自增ID
            // stmt.executeUpdate("ALTER TABLE countries AUTO_INCREMENT = 1");
        }
    }

    /**
     * 生成唯一的国家数据，确保国家名称不重复
     */
    private static List<Country> generateUniqueCountryData() {
        List<Country> countryList = new ArrayList<>(TOTAL_RECORDS);
        Set<String> usedNames = new HashSet<>(TOTAL_RECORDS);

        // 使用Fisher-Yates洗牌算法随机选择不重复的名称
        List<String> availableNames = new ArrayList<>(COUNTRY_NAMES);
        Collections.shuffle(availableNames, RANDOM);

        // 生成不重复的国家名称
        for (int i = 0; i < TOTAL_RECORDS; i++) {
            String name = availableNames.get(i);

            // 确保唯一性（理论上不需要，但作为防御性编程保留）
            if (!usedNames.add(name)) {
                name = generateUniqueName(usedNames, name);
            }

            countryList.add(new Country(i + 1, name));
        }

        return countryList;
    }

    /**
     * 生成唯一的国家名称
     */
    private static String generateUniqueName(Set<String> usedNames, String originalName) {
        // 提取基础名称（如果已经有后缀）
        String baseName = originalName;
        int suffixIndex = originalName.lastIndexOf('_');
        if (suffixIndex > 0) {
            try {
                Integer.parseInt(originalName.substring(suffixIndex + 1));
                baseName = originalName.substring(0, suffixIndex);
            } catch (NumberFormatException e) {
                // 不是数字后缀，使用完整名称作为基础
            }
        }

        int suffix = 1;
        String uniqueName;
        do {
            uniqueName = baseName + "_" + suffix++;
        } while (usedNames.contains(uniqueName));

        usedNames.add(uniqueName);
        return uniqueName;
    }

    /**
     * 将数据批量插入数据库
     */
    private static void insertToDatabase(List<Country> countryList) throws SQLException {
        String sql = "INSERT INTO countries (country_id, country_name) VALUES (?, ?)";

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            conn.setAutoCommit(false); // 手动提交事务

            for (int i = 0; i < countryList.size(); i++) {
                Country country = countryList.get(i);
                pstmt.setInt(1, country.getCountryId());
                pstmt.setString(2, country.getCountryName());
                pstmt.addBatch();

                // 每BATCH_SIZE条执行一次批处理
                if ((i + 1) % BATCH_SIZE == 0) {
                    pstmt.executeBatch();
                    pstmt.clearBatch();
                }
            }

            // 执行剩余批次
            if (countryList.size() % BATCH_SIZE != 0) {
                pstmt.executeBatch();
            }

            conn.commit(); // 提交事务

        } catch (SQLException e) {
            log.error("执行数据库操作失败", e);
            throw e;
        }
    }
}